package com.ziq.zcamp.community

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.Observer
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.bumptech.glide.Glide
import com.scwang.smart.refresh.horizontal.HorizontalFooter
import com.ziq.base.base.BaseFragment
import com.ziq.base.extension.binding
import com.ziq.base.extension.click
import com.ziq.base.extension.dp
import com.ziq.base.extension.launchWithTry
import com.ziq.zcamp.R
import com.ziq.zcamp.bean.post.PostSubject
import com.ziq.zcamp.databinding.FragmentCommunityTabBinding
import com.ziq.zcamp.login.ActionAfterLogin
import com.ziq.zcamp.login.LoginActivity
import com.ziq.zcamp.manager.*
import com.ziq.zcamp.view.CustomLinePagerIndicator
import com.ziq.zcamp.view.OrderPagerTitleView
import dagger.hilt.android.AndroidEntryPoint
import net.lucode.hackware.magicindicator.FragmentContainerHelper
import net.lucode.hackware.magicindicator.buildins.UIUtil
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator
import java.lang.reflect.Field

@AndroidEntryPoint
class CommunityTabFragment : BaseFragment(R.layout.fragment_community_tab){

    companion object {
        const val TARGET_TAB_INDEX = "tab_index"
        const val TARGET_TAB_FOLLOW = 0
        const val TARGET_TAB_RECOMMEND = 1
        const val TARGET_TAB_NEARBY = 2

        const val TITLE_FOLLOW = "关注"
        const val TITLE_RECOMMEND = "推荐"
        const val TITLE_NEARBY = "附近"


        fun createFragment(tab: Int = TARGET_TAB_RECOMMEND) : CommunityTabFragment {
            val fragment = CommunityTabFragment()
            val bundle = Bundle()
            bundle.putInt(TARGET_TAB_INDEX, tab)
            fragment.arguments = bundle
            return fragment
        }
    }

    private val binding : FragmentCommunityTabBinding? by binding()
    var initTabIndex = 0
    val titles = listOf<String>(TITLE_FOLLOW, TITLE_RECOMMEND, TITLE_NEARBY)

    private var isFirst = true
    override fun onResume() {
        super.onResume()
        if (isFirst){
            isFirst = false
            PostManager.requestSubject()
            CampLifeManager.requestMyCampData()
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding?.root

        initTabIndex = arguments?.getInt(TARGET_TAB_INDEX, TARGET_TAB_RECOMMEND) ?: 0

        binding?.root
        initMagicIndicator()
        initViewPager()
        handleTabSelected(initTabIndex)
        initPostStatus() //帖子上传状态栏
        initSubject() //专题栏
        binding?.postingBtn?.click {
            LoginActivity.checkLogin(object : ActionAfterLogin {
                @SuppressLint("CheckResult")
                override fun action() {
                    GlobalContextManager.mainHandler.postDelayed({
                        if(activity != null){
                            PostManager.showPostTypeSelector(requireActivity())
                        }
                    }, 500)
                }
            })
        }
    }

    private val mFragmentContainerHelper = FragmentContainerHelper()
    private fun initMagicIndicator() {
        val magicIndicator = binding?.magicIndicator
        val commonNavigator = CommonNavigator(requireContext())
        commonNavigator.notifyDataSetChanged()
        commonNavigator.isAdjustMode = false
        commonNavigator.adapter = object : CommonNavigatorAdapter() {
            override fun getCount(): Int {
                return titles.size
            }

            override fun getTitleView(context: Context, index: Int): IPagerTitleView {
                val simplePagerTitleView = OrderPagerTitleView(context)
                simplePagerTitleView.text = titles[index]
                simplePagerTitleView.selectedColor = Color.parseColor("#333333")
                simplePagerTitleView.normalColor = Color.parseColor("#999999")
                simplePagerTitleView.textSize = 14f
                simplePagerTitleView.setPadding(
                    UIUtil.dip2px(context, 12.0), 0,
                    UIUtil.dip2px(context, 12.0),0)
                simplePagerTitleView.setOnClickListener {
                    GlobalContextManager.getCurrentActivity()?.let {
                        PrivacyManager.checkPrivacy(it, action = {
                            binding?.viewPager?.isUserInputEnabled = PrivacyManager.isAgreedPrivacy()
                            handleTabSelected(index)
                        })
                    }
                }
                return simplePagerTitleView
            }

            override fun getIndicator(context: Context): IPagerIndicator {
                val indicator = CustomLinePagerIndicator(context)
                indicator.mode = LinePagerIndicator.MODE_EXACTLY
                indicator.setImageSrc(R.drawable.icon_place_dialog_tab_index)
                indicator.lineHeight = UIUtil.dip2px(context, 4.0).toFloat()
                indicator.lineWidth = UIUtil.dip2px(context, 30.0).toFloat()
                indicator.setColors(Color.parseColor("#000000"))
                return indicator
            }
        }
        commonNavigator.leftPadding = 6.dp
        commonNavigator.rightPadding = 6.dp
        magicIndicator?.navigator = commonNavigator
        mFragmentContainerHelper.attachMagicIndicator(magicIndicator)
    }
    private fun initViewPager() {
        binding?.viewPager?.adapter = object : FragmentStateAdapter(this) {
            override fun getItemCount(): Int {
                return titles.size
            }

            override fun createFragment(position: Int): Fragment {
                return when(position){
                    TARGET_TAB_FOLLOW -> CommunityFollowFragment()
                    TARGET_TAB_RECOMMEND -> CommunityRecommendFragment()
                    TARGET_TAB_NEARBY -> CommunityNearbyFragment()
                    else ->{
                        CommunityRecommendFragment()
                    }
                }
            }
        }
        binding?.viewPager?.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                handleTabSelected(position, isForViewPagerScroll = true)
            }
        })
        binding?.viewPager?.offscreenPageLimit = 3
        binding?.viewPager?.isUserInputEnabled = PrivacyManager.isAgreedPrivacy()
        if(binding?.viewPager != null){
            updateTouchSlop(binding?.viewPager!!)
        }
    }
    private var currentTabIndex = -1
    fun handleTabSelected(index: Int, isForViewPagerScroll: Boolean = false){
        if(currentTabIndex != index && index >= 0){
            currentTabIndex = index
            mFragmentContainerHelper.handlePageSelected(index)
            if(!isForViewPagerScroll){
                binding?.viewPager?.setCurrentItem(index, false)
            }

            val record = when(currentTabIndex){
                0 -> "follow"
                1 -> "rec"
                2 -> "nearby"
                else -> {
                    ""
                }
            }
        }
    }

    fun initPostStatus(){
        PostManager.uploadStatus.observe(viewLifecycleOwner) {
            when (it) {
                PostManager.UPLOAD_STATUS_IDLE -> {
                    binding?.clUploadBar?.visibility = View.GONE
                    binding?.tvUploadStatus?.text = ""
                    binding?.uploadProgressBar?.visibility = View.VISIBLE
                    binding?.tvUploadFail?.visibility = View.GONE
                }
                PostManager.UPLOAD_STATUS_START -> {
                    binding?.clUploadBar?.visibility = View.VISIBLE
                    binding?.tvUploadStatus?.text = "正在发布…"
                    binding?.uploadProgressBar?.visibility = View.VISIBLE
                    binding?.tvUploadFail?.visibility = View.GONE
                    var path = PostManager.getCoverPath()
                    if (path.isNotEmpty() && binding?.ivUploadCover != null) {
                        Glide.with(requireActivity()).load(path).into(binding?.ivUploadCover!!)
                    }
                }
                PostManager.UPLOAD_STATUS_SUCCESS -> {
                    binding?.tvUploadStatus?.text = "发布成功！"
                    binding?.uploadProgressBar?.visibility = View.VISIBLE
                    binding?.tvUploadFail?.visibility = View.GONE
                    binding?.clUploadBar?.visibility = View.GONE
                }
                PostManager.UPLOAD_STATUS_FAIL -> {
                    binding?.clUploadBar?.visibility = View.VISIBLE
                    binding?.tvUploadStatus?.text = "内容发布失败"
                    binding?.uploadProgressBar?.visibility = View.GONE
                    binding?.tvUploadFail?.visibility = View.VISIBLE
                }
            }
        }
        PostManager.process.observe(viewLifecycleOwner) {
            binding?.uploadProgressBar?.progress = it
            binding?.tvUploadProgress?.text = "$it%"
        }

        binding?.clUploadBar?.click {
        }
    }

    var subjectAdapter : SubjectAdapter? = null
    fun initSubject(){
        binding?.smartRefreshHorizontal?.setEnableRefresh(false)
        binding?.smartRefreshHorizontal?.setEnableLoadMore(false)
        binding?.smartRefreshHorizontal?.setEnableAutoLoadMore(false)
        binding?.smartRefreshHorizontal?.setFooterTriggerRate(0.6f)
        binding?.smartRefreshHorizontal?.setRefreshFooter(
            HorizontalFooter(View.inflate(requireContext(), R.layout.footer_home_subject, null)),
            30.dp, 30.dp)
        binding?.smartRefreshHorizontal?.setOnLoadMoreListener {
            binding?.smartRefreshHorizontal?.finishLoadMore(0)
            binding?.smartRefreshHorizontal?.resetNoMoreData()
            GlobalContextManager.getCurrentActivity()?.let {
                PrivacyManager.checkPrivacy(it, action = {
                    openMoreSubject(0)
                })
            }
        }
        subjectAdapter = SubjectAdapter(requireContext())
        binding?.rvSubject?.layoutManager = LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
        binding?.rvSubject?.adapter = subjectAdapter
        subjectAdapter?.subjectAdapterAction = object : SubjectAdapter.SubjectAdapterAction {
            override fun itemClick(item: PostSubject) {
                GlobalContextManager.getCurrentActivity()?.let {
                    PrivacyManager.checkPrivacy(it, action = {
                        openMoreSubject(item.id?:0)
                    })
                }

            }

            override fun moreClick() {
                GlobalContextManager.getCurrentActivity()?.let {
                    PrivacyManager.checkPrivacy(it, action = {
                        openMoreSubject(0)
                    })
                }
            }
        }

        PostManager.subjectList.observe(viewLifecycleOwner) {
            binding?.smartRefreshHorizontal?.setEnableLoadMore(it?.size?:0 >= 3)
            if(it?.size?:0 >= 2){ // 两个专题及以上则在首页显示专题入口
                binding?.clSubject?.visibility = View.VISIBLE
                subjectAdapter?.setData(it)
            } else {
                binding?.clSubject?.visibility = View.GONE
                subjectAdapter?.setData(listOf())
            }
        }

        launchWithTry(whenTry = {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                CampLifeManager.myCampData.collect{
                    subjectAdapter?.setCampData(it.camping_count?:0)
                }
            }
        })
    }


    fun updateTouchSlop(viewPager:ViewPager2){
        try {
            val recyclerViewField: Field = ViewPager2::class.java.getDeclaredField("mRecyclerView")
            recyclerViewField.isAccessible = true
            val recyclerView = recyclerViewField.get(viewPager) as RecyclerView
            val touchSlopField: Field = RecyclerView::class.java.getDeclaredField("mTouchSlop")
            touchSlopField.isAccessible = true
            val touchSlop = touchSlopField.get(recyclerView) as Int
            val targetTouchSlop = 25.dp
            touchSlopField.set(recyclerView, targetTouchSlop) //6 is empirical value
        } catch (ignore: Exception) {
        }
    }

    fun openMoreSubject(id:Int){
        if(PostManager.subjectList.value != null){
            val datas = arrayListOf<PostSubject>()
            datas.addAll(PostManager.subjectList.value!!)
            SubjectTabActivity.open(GlobalContextManager.appContext!!, datas, id)
        }
    }

}